﻿using System;
using CrossLayerCommunication;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;

namespace UnitTest
{
    [TestClass]
    public class TestOperationResultHelper
    {
        public class HelperClass {
            public string StringValue;
            public int IntValue;
        }

        [TestMethod]
        public void TestMerge()
        {
            Message.AllMessages.Clear();

            IOperationResult operationResult1 = OperationResult.OK,
                             operationResult2 = new OperationResult(MessageHelper.CreateOrGetMessage(-1));

            operationResult1.Merge(operationResult2);
            TestOperationResult.CheckOperationResult(operationResult1, expectedOperationWasSuccesfull: false, expectedNumberOfMessages: 1);
            Assert.AreEqual(-1, operationResult1.Messages.First().Id);
        }

        [TestMethod]
        public void TestMergeTwoDifferentOperationResults()
        {
            Message.AllMessages.Clear();

            IOperationResult<string> operationResult1 = new OperationResult<string>("Testing");
            IOperationResult operationResult2 = new OperationResult(MessageHelper.CreateOrGetMessage(-1));

            Assert.IsTrue(operationResult1.WasSuccessful);

            var resultOfMerge = operationResult1.Merge(operationResult2);

            Assert.AreEqual("Testing", resultOfMerge.Data);
            Assert.IsFalse(resultOfMerge.WasSuccessful);
            Assert.AreEqual(1, resultOfMerge.Messages.Count());
        }

        [TestMethod]
        public void TestMergeWithData()
        {
            IOperationResult<string> operationResult1 = new OperationResult<string>("Testing");
            IOperationResult<HelperClass> operationresult2 = new OperationResult<HelperClass>(new HelperClass());

            Assert.IsNull(operationresult2.Data.StringValue);

            operationresult2.Merge(operationResult1, (hc, s) => { hc.StringValue = s; });

            Assert.AreEqual("Testing", operationresult2.Data.StringValue);
        }

        [TestMethod]
        public void TestReplaceMessageKeyIfMessage()
        {
            IOperationResult operationResult = new OperationResult(MessageHelper.CreateOrGetMessage(-1));
            Assert.IsNull(operationResult.Messages.First().Key);
            operationResult.ReplaceMessageKeyIfMessage(MessageHelper.CreateOrGetMessage(-1), "Key");
            Assert.AreEqual("Key", operationResult.Messages.First().Key);
        }
    }
}
